<?php
namespace App\Blocks;

use App\Libs\Jiguang\JMessage;
use App\Models\Crowd;
use App\Models\Goods;
use App\Models\OrderInfos;
use App\Models\Orders;
use App\Models\UserCert;
use App\Models\UserFriends;
use App\Models\UserMoneyLog;
use App\Models\Users;
use App\Models\WechatUser;
use App\Models\UserWithdrawDeposit;
use DB;

class UserBlock {
    //通过id获取用户基本信息
    public function userInfo($uid){
        $userCertModel = new UserCert();
        $userModel = new Users();
        $crowdModel = new Crowd();
        $ordersModel = new Orders();

        $user = DB::table($userModel->getTable() . ' as u')
            ->select(
                'u.id',
                'u.nick_name',
                'u.mobile',
                'u.headimgurl',
                'u.created_at',
                'uc.status as user_cert_status',
                'u.wx_openid',
                'u.jg_im_username',
                'u.signature'
            )
            ->leftJoin($userCertModel->getTable() . ' as uc', 'uc.user_id', '=', 'u.id')
            ->where('u.id', $uid)
            ->whereNull('u.deleted_at') //条件查询，deleted_at为空值
            ->first();//获取一条数据,返回单个对象

        $user->crowd_num = DB::table($crowdModel->getTable())->where('uid', $uid)
            ->whereNull('deleted_at')->count();//获取用户的群

        //群收益
        $user->crowd_money = DB::table($crowdModel->getTable())
            ->select('id','name','income')
            ->where('uid',$uid)->get();
        $money=0;
        foreach ($user->crowd_money as $moneys) {
            $money = $money+(int)$moneys->income;
        }
        $user->money = $money;

        //月收益、昨日收益
        $Userid = DB::table($crowdModel->getTable())->select('id')->where('uid',$uid)->get();
        $ids = [];
        foreach ($Userid as $val){
            $ids[] = $val->id;
        }
        if (count($ids)<=0){
            $user->monthIcom = 0;
            $user->yesterdayIcom = 0;
        }else{
            $monthIcom = DB::table($ordersModel->getTable())
                ->select('pay_total')
                ->where('status',1)
                ->whereIN('crowd_id',$ids)
                ->whereBetween('created_at',
                    [
                        date('Y-m-01 00:00:00', strtotime(date("Y-m-d"))),
                        date('Y-m-d H:i:s',time())
                    ])
                ->sum('pay_total');
            $user->monthIcom = $monthIcom;
            $yesterdayIcom = DB::table($ordersModel->getTable())
                ->select('pay_total')
                ->where('status',1)
                ->whereIN('crowd_id',$ids)
                ->whereBetween('created_at',
                    [
                        date('Y-m-d 00:00:00',strtotime(date("Y-m-d",strtotime("-1 day")))),
                        date('Y-m-d 00:00:00',time())
                    ])
                ->sum('pay_total');
            $user->yesterdayIcom = $yesterdayIcom;
        }


        //返回进本信息和用户群
        return $user;
    }

    //流水
    public function UserWaste($uid){
        $CrowdModel = new Crowd();
        $userModel = new Users();
        $moneyLogModel = new UserMoneyLog();

        $userInfo = DB::table($userModel->getTable())
            ->select(
                'id',
                DB::raw('round(balance / 100,2) as balance')
            )
            ->where('id',$uid)
            ->first();

        if(!$userInfo){
            return false;
        }
        $CrowdIds = DB::table($CrowdModel->getTable())->select('id')->where('uid',$uid)->get();

        if (!$CrowdIds){
            $userInfo->monthIcom = 0;
            $userInfo->yesterdayIcom = 0;
            $userInfo->waste = [];
            return $userInfo;
        }

        //月收入
        $monthIcom = DB::table($moneyLogModel->getTable())
            ->where('u_id',$uid)
            ->whereBetween('created_at',
                [
                    date('Y-m-01 00:00:00', strtotime(date("Y-m-d"))),
                    date('Y-m-d H:i:s',time())
                ])
            ->sum('money');

        //昨日收入
        $yesterdayIcom = DB::table($moneyLogModel->getTable())
            ->where('u_id',$uid)
            ->whereBetween('created_at',
                [
                    date('Y-m-d 00:00:00',strtotime(date("Y-m-d",strtotime("-1 day")))),
                    date('Y-m-d 00:00:00',time())
                ])
            ->sum('money');



        $orderSell= DB::table($moneyLogModel->getTable())
                ->select('id',DB::raw('round(money / 100, 2) as money'),'created_at','remake as name','type')
                ->where('u_id',$uid)
                ->whereYear('created_at',date('Y',time()))
                ->get();

        foreach ($orderSell as $order){
            $order->month = date('m',strtotime($order->created_at));
        }


        $waste = [];
        foreach ($orderSell as $value){
            $waste[] = $value;
        }
        if (count($waste)>0){
            foreach($waste as $key=>$v){
                $arr[$key]['ctime_str'] = strtotime($v->created_at);
                $ctime_str[] = $arr[$key]['ctime_str'];
            }
            array_multisort($ctime_str,SORT_DESC,$waste);
        }
        $userInfo->monthIcom = $monthIcom / 100;
        $userInfo->yesterdayIcom = $yesterdayIcom / 100;

        $month =  range(1,12);
        $wasteData=[];
        foreach ($waste as $info){
            if (in_array($info->month,$month)){
                $wasteData[$info->month][] = $info;
            }
        }
        krsort($wasteData);
        $userInfo->waste = $wasteData;
        return $userInfo;
    }

    //通过手机号获取用户信息
    public function userInfoByMobile($mobile){
        $userCertModel = new UserCert();
        $userModel = new Users();
        $crowdModel = new Crowd();

        $user = DB::table($userModel->getTable() . ' as u')
            ->select(
                'u.id',
                'u.nick_name',
                'u.mobile',
                'u.headimgurl',
                'u.created_at',
                'uc.status as user_cert_status',
                'u.password',
                'u.wx_openid',
                'u.jg_im_username',
                'u.signature'
            )
            ->leftJoin($userCertModel->getTable() . ' as uc', 'uc.user_id', '=', 'u.id')
            ->where('u.mobile', $mobile)
            ->whereNull('u.deleted_at')
            ->first();

        if(!$user){
            return [];
        }

        $user->crowd_num = DB::table($crowdModel->getTable())->where('uid', $user->id)
            ->whereNull('deleted_at')->count();

        return $user;
    }

    private function userCertSql($search){
        $userCertModel = new UserCert();
        $sql = DB::table($userCertModel->getTable())
            ->whereNull('deleted_at');
        //根据真实姓名查询用户实名信息
        if(isset($search['real_name'])){
            $sql->where('real_name', 'like', "%".$search['real_name']."%");
        }
        //根据手机号查询用户实名信息
        if(isset($search['mobile'])){
            $sql->where('mobile', $search['mobile']);
        }
        return $sql;
    }

    //获取实名列表
    public function userCertList($search=[], $page=0, $pageSize=5){
        $sql = $this->userCertSql($search);

        $list = $sql->orderBy('created_at')
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->get();
        return $list;
    }

    //获取实名列表分页
    public function userCertListPagination($search=[], $page=1, $pageSize=5)
    {
        $sql = $this->userCertSql($search);
        return [
            'total' => $sql->count(),
            'pageSize' => $pageSize,
            'current' => $page
        ];
    }

    //更新实名状态
    public function updateUserCertStatus($id, $status){
        $userCertModel = new UserCert();
        return DB::table($userCertModel->getTable())->where('id', $id)
            //只有是未审核的状态才能修改
            ->where('status', 0)
            ->update([
                'status' => $status
            ]);
    }

    //添加用户，在添加用户的时候，需要注册极光IM
    public function addUser($data){
        $userModel = new Users();

        try{
            DB::beginTransaction();

            $userId = DB::table($userModel->getTable())->insertGetId($data);
            if(!$userId){
                return false;
            }

            //极光IM注册
            $jMessage = new JMessage();
            $jMessage->userRegister($data['jg_im_username']);

            $update = [];
            if(isset($data['headimgurl'])){
                $pathinfo = pathinfo($data['headimgurl']);
                $extension = isset($pathinfo['extension'])?$pathinfo['extension']:'png';
                file_put_contents("/tmp/{$userId}.{$extension}",file_get_contents($data['headimgurl']));
                $update['avatar'] = $jMessage->reUpload('image', "/tmp/{$userId}.{$extension}");
            }

            if(isset($data['nick_name'])){
                $update['nickname'] = $data['nick_name'];
            }

            if(!empty($update)) {
                $jMessage->userUpdate($data['jg_im_username'], $update);
            }

            DB::commit();
            return $userId;

        }catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception);
            return false;
        }
    }

    public function saveUserByWeixin($data){
        try {
            if (!isset($data['openid'])) {
                return ['error' => '参数错误'];
            }

            $userModel = new Users();
            $wechatUser = new WechatUser();

            DB::beginTransaction();

            $userData = [
                'nick_name'         => $data['nickname'],
                'wx_openid'         => $data['openid'],
                'headimgurl'        => $data['headimgurl'],
                'jg_im_username'    => 'chaihe_'.$data['openid'],
                'created_at'        => date('Y-m-d H:i:s', time())
            ];

            $userInfo = DB::table($userModel->getTable())
                ->where('wx_openid', $data['openid'])
                ->first();
            if ($userInfo) {
                $userId = $userInfo->id;
                DB::table($userModel->getTable())
                    ->where('wx_openid', $data['openid'])
                    ->update($userData);
            } else {
                $userId = $this->addUser($userData);
            }

            if (DB::table($wechatUser->getTable())
                ->where('openid', $data['openid'])
                ->first()) {
                DB::table($wechatUser->getTable())
                    ->where('openid', $data['openid'])
                    ->update($data);
            } else {
                if(!DB::table($wechatUser->getTable())->insertGetId($data)){
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return $userId;

        }catch (\Exception $exception){
            \Log::error($exception);
            return false;
        }
    }

    public function bindWeixin($uid , $data){
        try {
            if (!isset($data['openid'])) {
                return ['error' => '参数错误'];
            }

            $userModel = new Users();
            $wechatUser = new WechatUser();

            DB::beginTransaction();

            $userInfo = DB::table($userModel->getTable())
                ->where('wx_openid', $data['openid'])
                ->first();
            if ($userInfo) {
                return false;
            } else {
                $userId = DB::table($userModel->getTable())
                    ->where('id', $uid)
                    ->update(['wx_openid' => $data['openid']]);
            }

            if (DB::table($wechatUser->getTable())
                ->where('openid', $data['openid'])
                ->first()) {
                DB::table($wechatUser->getTable())
                    ->where('openid', $data['openid'])
                    ->update($data);
            } else {
                if(!DB::table($wechatUser->getTable())->insertGetId($data)){
                    DB::rollBack();
                    return false;
                }
            }

            DB::commit();
            return $userId;

        }catch (\Exception $exception){
            \Log::error($exception);
            return false;
        }
    }

    public function getUserByWxOpenid($openid){
        $userModel = new Users();
        $userCertModel = new UserCert();
        $wechatUser = new WechatUser();
        return DB::table($userModel->getTable() .' as u')
            ->select(
                'u.id',
                'u.nick_name',
                'u.mobile',
                'u.headimgurl',
                'u.created_at',
                'uc.status as user_cert_status',
                'u.password',
                'u.wx_openid',
                'u.jg_im_username',
                'u.signature'
            )
            ->leftJoin($userCertModel->getTable() . ' as uc', 'uc.user_id', '=', 'u.id')
            ->leftJoin($wechatUser->getTable() .' as wx', 'u.wx_openid', '=', 'wx.openid')
            ->where('u.wx_openid', $openid)
            ->whereNull('u.deleted_at')
            ->first();
    }

    public function UserWithRraw($uid,$money){
        $UserWithrwaModel = new UserWithdrawDeposit();
        $UserModel = new Users();
        $balane = DB::table($UserModel->getTable())->select('balance')->where('id',$uid)->first();
        if (!$balane && $money>$balane->balance){
            \Log::debug(1);
            return false;
        }

        try{
            DB::beginTransaction();

            if(
                !DB::table($UserWithrwaModel->getTable())->insert(
                [
                    'uid'=>$uid,
                    'money'=>$money,
                    'status'=>0,
                    'created_at'=> date('Y-m-d H:i:s',time()),
                ]
            )
            ){
                \Log::debug(1);
                DB::rollBack();
                return false;
            }

            if(
                !DB::table($UserModel->getTable())->where('id',$uid)
                ->decrement('balance',$money)
            ){
                \Log::debug(1);
                DB::rollBack();
                return false;
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            \Log::error($exception);
            return false;
        }


    }


    public function UserBalance($uid){
        $UserModel = new Users();
        return DB::table($UserModel->getTable())->select('balance')->where('id',$uid)->first();
    }

    public function getUserFriendReq($userId, $page = 1, $pageSize = 20){
        $userFriendModel = new UserFriends();
        $userModel = new Users();
        $user = DB::table($userFriendModel->getTable(). ' as uf')
            ->select(
                'uf.*',
                "u.nick_name",
                "u.mobile",
                "u.email",
                "u.wx_openid",
                "u.headimgurl",
                "u.password",
                "u.signature",
                "u.grade",
                "u.jg_im_username"
            )
            ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 'uf.user_id')
            ->whereNull('u.deleted_at')
            ->where('uf.friend_id', $userId)
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('uf.status', 'asc')
            ->orderBy('uf.create_time', 'desc')
            ->get();

        foreach ($user as $value){
            $value->create_time = strtotime($value->create_time);
        }

        return $user;
    }

    public function userFriendRes($userId, $friendId, $status){
        \Log::debug($userId);
        \Log::debug($friendId);
        \Log::debug($status);
        $userFriendModel = new UserFriends();
        $userModel = new Users();

        if($status == 2){
            if(DB::table($userFriendModel->getTable())
                ->where('friend_id', $userId)
                ->where('id', $friendId)
                ->where('status', 0)
                ->update(['status' => 2])){
                return true;
            }else{
                return false;
            }
        }elseif($status == 1) {
            $user = DB::table($userFriendModel->getTable() . ' as uf')
                ->select(
                    'uu.jg_im_username as from_user',
                    'u.jg_im_username as to_user'
                )
                ->leftJoin($userModel->getTable() . ' as uu', 'uu.id', '=', 'uf.user_id')
                ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 'uf.friend_id')
                ->whereNull('u.deleted_at')
                ->where('uf.status', 0)
                ->where('uf.id', $friendId)
                ->where('uf.friend_id', $userId)
                ->first();

            if($user){
                if(!empty($user->from_user) && !empty($user->to_user)){
                    $lib = new JMessage();
                    if($lib->friendAdd($user->to_user, [$user->from_user])){
                        if(DB::table($userFriendModel->getTable())
                            ->where('friend_id', $userId)
                            ->where('id', $friendId)
                            ->where('status', 0)
                            ->update(['status' => 1])){
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        return false;
                    }
                }
            }else{
                return false;
            }
        }

        return true;
    }


    private function withdrawSql($search){
        $Users                  = new Users();
        $UserWithdrawDeposit    = new UserWithdrawDeposit();

        $sql = DB::table($UserWithdrawDeposit->getTable() . ' as w')
            ->select(
                'w.id',
                'w.money',
                'w.created_at',
                DB::raw("date_format(".env('DB_PREFIX')."w.created_at, '%c') as mouth"),
                'u.nick_name',
                'u.headimgurl'
            )
            ->leftJoin($Users->getTable() . ' as u', 'u.id', '=', 'w.uid')
            ->whereNull('w.deleted_at');

        if(isset($search['user_id'])){
            $sql->where('w.uid', $search['user_id']);
        }
        return $sql;
    }
    public function withdrawList($search, $page, $pageSize){
        $sql = $this->withdrawSql($search);

        $list = $sql->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('w.created_at', 'desc')
            ->get();

        return $list;
    }

    public function withdrawListPagination(array $search, int $page = 1, int $pageSize = 20){
        $sql = $this->withdrawSql($search);
        return [
            'total' => $sql->count(),
            'pageSize' => $pageSize,
            'current' => $page,
        ];
    }



    //用户列表

    public function userListSql($search){
        $user = new Users();
        $sql = DB::table($user->getTable())
            ->select('id','nick_name','mobile','headimgurl','wx_openid','signature','jg_im_username','created_at')
            ->whereNull('deleted_at');
        if(isset($search['userMsg'])){
            $sql->where('nick_name', 'like', "%".$search['userMsg']."%")->orwhere('mobile', 'like', "%".$search['userMsg']."%");
        }
        return $sql;
    }
    public function userList($search, $page, $pageSize){
        $sql = $this->userListSql($search);

        $list = $sql->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('created_at', 'desc')
            ->get();

        return $list;
    }

    public function userListPagination(array $search, int $page = 1, int $pageSize = 20){
        $sql = $this->userListSql($search);
        return [
            'total' => $sql->count(),
            'pageSize' => $pageSize,
            'current' => $page,
        ];
    }
}
